package com.itheima.demo1create;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * 个人练习类
 *
 * @author 小赫
 * <p>2025/3/16 13:42
 */
public class ThreadDemo5My {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 创建并启动一个继承自Thread类的线程
        MyThread1 m1 = new MyThread1();
        m1.start();

        // 创建并启动一个实现了Runnable接口的线程
        MyRunnable1 r1 = new MyRunnable1();
        Thread t1 = new Thread(r1);
        t1.start();

        // 使用Lambda表达式创建并启动一个线程
        new Thread(() -> new fangfa().a(Thread.currentThread().getName())).start();

        // 创建并启动一个实现了Callable接口的线程，并获取其返回值
        MyCallable1 c1 = new MyCallable1();
        FutureTask<Integer> ft1 = new FutureTask<>(c1);
        Thread t2 = new Thread(ft1);
        t2.start();
        System.out.println("Callable 结果为:" + ft1.get());

    }
}

// 定义一个包含方法a的类，用于打印线程名称和累加结果
class fangfa {
    public void a(String name) {
        int a = 0;
        for (int i = 1; i <= 3; i++) {
            a += i;
            System.out.println(name + "=" + a);
        }
    }
}

// 继承自Thread类的线程类
class MyThread1 extends Thread {
    @Override
    public void run() {
        fangfa f = new fangfa();
        f.a(Thread.currentThread().getName());
    }
}

// 实现Runnable接口的线程类
class MyRunnable1 implements Runnable {
    @Override
    public void run() {
        fangfa f = new fangfa();
        f.a(Thread.currentThread().getName());
    }
}

// 实现Callable接口的线程类，返回一个整数结果
class MyCallable1 implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        int a = 0;
        for (int i = 1; i <= 3; i++) {
            a += i;
            System.out.println(Thread.currentThread().getName() + "=" + a);
        }
        return a;
    }
}